<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="协议标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入协议标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="客户" prop="customerId">
        <el-select v-model="queryParams.customerId" placeholder="请选择客户" clearable size="small">
          <el-option
            v-for="customer in customers"
            :key="customer.id"
            :label="customer.supplier"
            :value="customer.id"
          />
        </el-select>
      </el-form-item> -->
     <!-- <el-form-item label="是否默认" prop="isDefault">
        <el-select v-model="queryParams.isDefault" placeholder="请选择是否默认" clearable size="small">
          <el-option
            v-for="dict in dict.type.isDefault"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in dict.type.status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['basicsystem:agreement:add']"
        >新增</el-button>
      </el-col>
     <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-paperclip"
          size="mini"
          :disabled="single"
          @click="handleCustomer"
        >客户</el-button>
      </el-col> -->
      <el-col :span="1.5">
       <el-dropdown @command="handleCommand">
          <el-button :disabled="multiple" size="mini" type="danger">
            批量操作<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="enabled" ><i class="el-icon-circle-plus-outline"></i>启用</el-dropdown-item>
            <el-dropdown-item command="disabled" ><i class="el-icon-remove-outline"></i>停用</el-dropdown-item>
            <!-- <el-dropdown-item command="delete" v-hasPermi="['basicsystem:agreement:remove']"><i class="el-icon-delete"></i>删除</el-dropdown-item> -->
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['basicsystem:agreement:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['basicsystem:agreement:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['basicsystem:agreement:export']"
        >导出</el-button>-->
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" max-height="620px" :data="agreementList" @selection-change="handleSelectionChange"  row-key="id"  :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="id" v-if="false" align="center" prop="id" />
      <el-table-column label="协议标题" align="center" prop="title" />
      <el-table-column label="客户" align="center" prop="customerId" :formatter="customerFormat"/>
      <el-table-column label="生效时间" align="center" prop="effectTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.effectTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="失效时间" align="center" prop="invalidTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.invalidTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
     <!-- <el-table-column label="是否默认" align="center" prop="isDefault">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.isDefault" :value="scope.row.isDefault"/>
        </template>
      </el-table-column> -->
      <el-table-column label="状态" align="center" prop="status" >
        <template slot-scope="scope" >
          <span v-if="scope.row.parentId != 0"><dict-tag :options="dict.type.agreement_status" :value="scope.row.status"/></span>
          <span v-else><dict-tag :options="dict.type.status" :value="scope.row.status"/></span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="新增人" align="center" prop="createName" /> -->
      <el-table-column label="新增时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
             plain icon="el-icon-search"
            @click="handleDetail(scope.row)"
             v-if="scope.row.parentId ==0 "
            v-hasPermi="['basicsystem:agreement:edit']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
             plain icon="el-icon-search"
            @click="handleCopy(scope.row)"
             v-if="scope.row.parentId == 0 "
            v-hasPermi="['basicsystem:agreement:edit']"
          >复制</el-button>
<!--          <el-popconfirm
            title="确认该协议立即生效？"
            @confirm="handleEffect(scope.row)"
            v-if="scope.row.status !='2' && scope.row.parentId ==0 && scope.row.children !=undefined"
          >
            <el-button  slot="reference" size="mini" type="text"  plain icon="el-icon-video-play">立即生效</el-button>
          </el-popconfirm>
          <el-popconfirm
            title="确认该协议立即失效？"
            @confirm="handleEffect(scope.row)"
            v-if="scope.row.status =='2' && scope.row.parentId ==0 && scope.row.children !=undefined"
          >
            <el-button  slot="reference" size="mini" type="text"  plain icon="el-icon-video-pause">立即失效</el-button>
          </el-popconfirm> -->
          <el-button
            size="mini"
            type="text"
             plain icon="el-icon-edit"
            v-if="scope.row.status =='0' && scope.row.parentId ==0 "
            @click="handleUpdate(scope.row)"
            v-hasPermi="['basicsystem:agreement:edit']"
          >修改</el-button>
          <el-button
            type="text"
            plain
            icon="el-icon-paperclip"
            size="mini"
            v-if="scope.row.status =='1' && scope.row.parentId ==0 "
            @click="handleCustomer(scope.row)"
          >客户</el-button>
          <el-button
            size="mini"
            type="text"
            plain
            icon="el-icon-delete"
            v-if="scope.row.status =='0' && scope.row.parentId ==0 "
            @click="handleDelete(scope.row)"
            v-hasPermi="['basicsystem:agreement:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 选配客户对话框 -->
    <el-dialog title="协议设置客户" :visible.sync="customerOpen" width="1000px" append-to-body>
      <el-form ref="customerForm" :model="customerForm" :rules="rules">
        <el-row >
          <el-col >
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAddCustomerItem">添加</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" :disabled="customerForm.multiple" icon="el-icon-delete" size="small" @click="handleDeleteCustomerItem">删除</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="success" :disabled="customerForm.multiple" icon="el-icon-edit" size="small" @click="handleUpdateCustomerItem">批量修改时间</el-button>
              </el-col>
              <el-col :span="1.5"  v-if="!customerForm.multiple">
                <el-date-picker size="small"
                  v-model="customerForm.effectTime"
                  type="datetime"
                  placeholder="选择生效时间"
                  :picker-options="pickerOptions"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :clearable="false"
                  :editable="false"
                  >
                </el-date-picker> -
                <el-date-picker size="small"
                  v-model="customerForm.invalidTime"
                  type="datetime"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择失效时间"
                  :picker-options="pickerOptions1"
                  :clearable="false"
                  :editable="false"
                  >
                </el-date-picker>
              </el-col>
            </el-row>
            <el-table :data="customerForm.customerList" :row-class-name="rowItemIndex" size="small" :max-height="380" @selection-change="handleCustomerItemSelectionChange">
              <!-- <el-table-column label="序号" align="center" prop="index" width="50" /> -->
              <el-table-column type="selection" width="50" align="center" class-name="allowDrag"/>
              <el-table-column label="客户" prop="customerId" align="center"  width="200">
                <template slot-scope="scope">
                  <el-form-item   label-width="0" :prop="'customerList.' + scope.$index + '.customerId'" :rules="rules.customerId">
                    <el-select v-model="scope.row.customerId" :disabled="scope.row.status =='2'" @change="handleSelectCustomer(scope.row,scope.$index)"  @visible-change="handleCustomerVisibelChange($event,scope.$index)">
                      <!-- <el-select v-model="scope.row.customerId" @visible-change="handleSelectCustomer($event,scope.$index)"> -->
                      <el-option  v-for="item in customerTransferData" :label="item.label" :key="item.key" :value="item.key" v-bind:disabled="item.disabled" ></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="生效时间" align="center" prop="effectTime" width="240">
                <template slot-scope="scope">
                  <el-form-item   label-width="0" :prop="'customerList.' + scope.$index + '.effectTime'" :rules="rules.effectTime">
                    <el-date-picker size="small"
                      v-model="scope.row.effectTime"
                      type="datetime"
                      placeholder="选择生效时间"
                      :picker-options="pickerOptions"
                      format="yyyy-MM-dd HH:mm:ss"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      :clearable="false"
                      :editable="false"
                      :disabled="scope.row.status =='2'"
                      >
                    </el-date-picker>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="失效时间" align="center" prop="invalidTime" width="240">
                <template slot-scope="scope" >
                  <el-form-item   label-width="0" :prop="'customerList.' + scope.$index + '.invalidTime'" :rules="rules.invalidTime">
                    <el-date-picker size="small"
                      v-model="scope.row.invalidTime"
                      type="datetime"
                      format="yyyy-MM-dd HH:mm:ss"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      placeholder="选择失效时间"
                      :picker-options="pickerOptions1"
                      :clearable="false"
                      :editable="false"
                      :disabled="scope.row.status =='2'"
                      >
                    </el-date-picker>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="状态" prop="status"  align="center">
                <template slot-scope="scope"  v-if="customerForm.isUpdate">
                   <el-form-item   >
                      <dict-tag :options="dict.type.agreement_status" :value="scope.row.status"/>
                   </el-form-item>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
       <el-button type="primary" :disabled="customerForm.customerList.length>0?false:true" @click="submitCustomerForm">确 定</el-button>
        <el-button @click="customerCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改客户协议价管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1300px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-row>
          <el-col :span="17">
            <el-form-item label="协议标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入协议标题" :disabled="isRealOnly"/>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <!-- <el-form-item label="客户" prop="customerId">
              <el-select v-model="form.customerId" placeholder="请选择客户" filterable size="small" :disabled="isRealOnly">
                <el-option
                  v-for="customer in customers"
                  :key="customer.id"
                  :label="customer.supplier"
                  :value="customer.id"
                />
              </el-select>
            </el-form-item> -->
            <el-form-item label="协议系数" prop="saleRatio">
              <el-input-number v-model="form.saleRatio"  :step="0.1" :min="0.1" :max="10" @change="changePurchasePrice"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
       <!-- <el-row>
          <el-col :span="16">
            <el-form-item label="生效时间" prop="effectTime">
              <el-date-picker clearable size="small"
                v-model="effectTimeRange"
                type="datetimerange"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择生效时间"
                :disabled="isRealOnly">
              </el-date-picker>
            </el-form-item>
          </el-col>
           <el-col :span="8">
            <el-form-item label="失效时间" prop="invalidTime">
              <el-date-picker clearable size="small"
                v-model="form.invalidTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择失效时间"
                :picker-options="pickerOptions"
                :disabled="isRealOnly">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
             <el-form-item label="客户" prop="customerId">
              <el-select v-model="form.customerId" placeholder="请选择客户" filterable size="small" :disabled="isRealOnly">
                <el-option
                  v-for="customer in customers"
                  :key="customer.id"
                  :label="customer.supplier"
                  :value="customer.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="协议系数" prop="saleRatio">
              <el-input-number v-model="form.saleRatio"  :step="0.1" :min="0.1" :max="10" @change="changePurchasePrice"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-divider content-position="center">协议商品详情信息</el-divider>
        <el-row :gutter="10" class="mb8">
            <!-- <el-col :span="9"></el-col> -->
           <!-- <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddZnAgreementDetail">添加</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteZnAgreementDetail">删除</el-button>
            </el-col> -->
            <el-col :span="1.5">
              <el-input v-model="material.queryParams.name" placeholder="请输入商品名称\首字母\条码" clearable size="small" @clear="resetMaterialQuery"
                @keyup.enter.native="handleMaterialQuery" />
            </el-col>
            <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleMaterialQuery">定位</el-button>
                <el-button icon="el-icon-refresh-left" size="mini" @click="resetMaterialQuery" v-if="isSearch">返回列表</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="refreshMaterialQuery" v-if="!isSearch">刷新商品</el-button>
            </el-col>
            <!-- <el-col :span="9"></el-col> -->
        </el-row>
        <el-table v-loading="subLoading" :data="znAgreementDetailCollection" :row-class-name="rowZnAgreementDetailIndex" @selection-change="handleZnAgreementDetailSelectionChange" ref="znAgreementDetail" :max-height="380" >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="商品ID" v-if="false" prop="materialId"/>
          <el-table-column label="商品名称" prop="materialName"/>
          <el-table-column label="条码" prop="materialBarCode"/>
          <el-table-column label="规格" align="center" prop="materialStandard" />
          <el-table-column label="型号" align="center" prop="materialModel" />
          <!-- <el-table-column label="颜色" align="center" prop="materialColor" /> -->
          <el-table-column label="类别" align="center" prop="materialCategoryName" />
          <el-table-column label="单位" align="center" prop="materialUnit" />
          <!-- <el-table-column label="保质期" align="center" prop="materialExpiryNum" /> -->
          <el-table-column label="采购价" align="center" prop="purchasePrice" />
          <el-table-column label="协议价" prop="salePrice" align="center">
            <template slot-scope="scope">
              <el-input type="number" v-model="scope.row.salePrice" placeholder="请输入协议价" :disabled="isRealOnly" @blur="changeML(scope.row,scope.$index)"/>
            </template>
          </el-table-column>
          <el-table-column label="毛利率" prop="mlRatio" >
            <template slot-scope="scope">
              {{(scope.row.mlRatio*100).toFixed(2)+'%'}}
            </template>
          </el-table-column>
          <el-table-column label="顺序" prop="orderNo" align="center">
            <template slot-scope="scope">
              <!-- <el-input-number v-model="scope.row.orderNo" :min="0" placeholder="请输入顺序" :disabled="isRealOnly" @blur="handleOrder"/> -->
              <el-input type="number" v-model="scope.row.orderNo" placeholder="请输入顺序" :disabled="isRealOnly" @blur="handleOrder(scope,scope.column)"/>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-show="!isRealOnly">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAgreement, getAgreement, delAgreement, addAgreement, updateAgreement, updateAgreementStatus,selectCustomerListByAgreementId,doCustomer } from "@/api/basicsystem/agreement";
import { listAllMaterial } from "@/api/material/material";
import {parseTime} from "@/utils/ruoyi";
import Sortable from 'sortablejs';
import * as math from 'mathjs'
export default {
  name: "Agreement",
  dicts: ['isDefault','agreement_status','status'],
  data() {
    return {
      //effectTime
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
      },
      //invalidTime
      pickerOptions1: {
        disabledDate(time) {
          const date = new Date();
         date.setTime(date.getTime() + 3600 * 1000 * 24 * 1 -10000);
          return time.getTime() < date;
        },
      },
      // 遮罩层
      loading: true,
      subLoading:true,
      // 选中数组
      ids: [],
      //可启用
      enableIds:[],
      //可停用idss
      disableIds:[],
      // 子表选中数据
      checkedZnAgreementDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户协议价管理表格数据
      agreementList: [],
      effectTimeRange:[],
      // 协议商品详情表格数据
      znAgreementDetailList: [],
      // 协议商品详情表格数据(显示集合)
      znAgreementDetailCollection: [],
      //协议商品详情表格是否查询
      isSearch:false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //协议价选配客户
      customerOpen:false,
      //是否只读
      isRealOnly:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        customerId: null,
        isDefault: null,
        status: null,
        updateName: null,
        tenantId: null,
        deleteFlag: null,
        params:{
          // isOverdue:'-1'
        }
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title:[
          { required: true, message: "协议标题不能为空", trigger: "blur" }
        ],
        // effectTime:[
        //   { required: true, message: "生效时间不能为空", trigger: "blur" }
        // ],
        // invalidTime:[
        //   { required: true, message: "失效时间不能为空", trigger: "blur" }
        // ],
        customerId:[
          {required: true, message: "客户不能为空", trigger: "blur"}
        ]
      },
      //选择商品窗口
      material:{
        // 查询参数
        queryParams: {
          // pageNum: 1,
          // pageSize: 10,
          // categoryId:null,
          // depotId:null,
          // params:{
          //   saleRatio:null
          // }
        },
        //类型树
        materialcategoryOptions:[],
        //当前选择商品的行号
        currentSelectRowNumber:0,
      },
      //客户数据
      customers:[],
      //客户穿梭框数据
      customerTransferData:[],
      //已选择客户列表
      selectedCustomers:[],
      selectAgreeId:null,
      customerForm:{
        // 非多个禁用
        multiple: true,
        agreementId:null,
        customerList:[],
        checkedCustomerItem: [],
        checkedCustomerIds:[],
        customerIdList:[],
        isUpdate:false,
        effectTime:null,
        invalidTime:null
      }
    };
  },
  watch:{
    'customerForm.multiple':function(n,o){
        console.log(n)
        if(!n){
           this.customerForm.effectTime = this.customerForm.customerList[0].effectTime;
           this.customerForm.invalidTime = this.customerForm.customerList[0].invalidTime
        }else{
           this.customerForm.effectTime = null;
           this.customerForm.invalidTime = null;
        }
    }
  },
  created() {
    this.getSuppliers({'type':'客户'}).then(response => {
      // console.log(response.data)
      this.customers = response.data;
      // this.customerTransferData =
      this.customers.forEach(item =>{
        this.customerTransferData.push({key:item.id,label:item.supplier})
      })
    });
    this.getList();
  },
  methods: {
    handleSelectCustomer(row,index){
        const customerIdList = this.customerForm.customerIdList;
        this.customerTransferData.forEach(item =>{
           // console.log(customerIdList.indexOf(item.key))
           if(customerIdList.indexOf(item.key)>-1){
             item.disabled =true
           }else{
             item.disabled =false
           }
        });
    },
    //下拉框点击的时候更新选项
    handleCustomerVisibelChange(callback,index){
      if(callback){

      }
    },
    /** 复选框选中数据 */
    handleCustomerItemSelectionChange(selection) {
      this.customerForm.checkedCustomerIds = selection.map(item => item.customerId)
      this.customerForm.checkedCustomerItem = [];
      selection.forEach(item => {
        console.log(item)
        if(item.parentId ==0 && item.status=='0'){
          this.customerForm.checkedCustomerItem.push(item.index)
        }else if(item.parentId ==0 && item.status=='1'){
          this.customerForm.checkedCustomerItem.push(item.index)
        }else{
           this.customerForm.checkedCustomerItem.push(item.index)
        }
      })
      this.customerForm.multiple = !selection.length
    },

    /** 客户批量修改生失效时间按钮操作 */
    handleUpdateCustomerItem(){
      if (this.customerForm.checkedCustomerIds.length == 0) {
        this.$modal.msgError("请先选择要修改生失效时间的客户");
      } else {
        const checkedCustomerIds = this.customerForm.checkedCustomerIds;
        const customerIdList = this.customerForm.customerList.map(item => item.customerId);
        let that_ = this;
        this.customerForm.customerList.forEach(item =>{
          console.log(item)
           if(checkedCustomerIds.indexOf(item.customerId)>-1){
            item.effectTime = that_.customerForm.effectTime
            item.invalidTime = that_.customerForm.invalidTime
           }
        });
      }
    },
     /** 客户删除按钮操作 */
    handleDeleteCustomerItem(){
      if (this.customerForm.checkedCustomerItem.length == 0) {
        this.$modal.msgError("请先选择要删除的客户");
      } else {
        const customerList = this.customerForm.customerList;
        const checkedCustomerItem = this.customerForm.checkedCustomerItem;
        this.customerForm.customerList = customerList.filter(function(item) {
          return checkedCustomerItem.indexOf(item.index) == -1
        });
        this.customerForm.customerIdList = this.customerForm.customerList.map(item => item.customerId);
        const customerIdList = this.customerForm.customerList.map(item => item.customerId);
        this.customerTransferData.forEach(item =>{
           console.log(customerIdList.indexOf(item.key))
           if(customerIdList.indexOf(item.key)>-1){
             item.disabled =true
           }else{
             item.disabled =false
           }
        });
      }
    },
    /** 客户添加按钮操作 */
    handleAddCustomerItem() {
        let obj = {};
        let end = new Date();
        end.setTime(end.getTime() + 3600 * 1000 * 24 * 1 -1000);
        obj.customerId = null;
        obj.effectTime = this.parseTime(new Date());
        obj.invalidTime = this.parseTime(end);
        this.customerForm.customerList.push(obj);
        const customerIdList = this.customerForm.customerList.map(item => item.customerId);
        this.customerTransferData.forEach(item =>{
           console.log(customerIdList.indexOf(item.key))
           if(customerIdList.indexOf(item.key)>-1){
             item.disabled =true
           }else{
             item.disabled =false
           }
        });
    },
    /** 客户列表子序号 */
    rowItemIndex({ row, rowIndex }) {
        row.index = rowIndex + 1;
    },
    /** 复制按钮操作 */
    handleCopy(row){
      this.reset();
      this.subLoading = true;
      this.open = true;
      this.title = "复制协议";

      this.effectTimeRange.push(this.form.effectTime  !=null?parseTime(this.form.effectTime , '{y}-{m}-{d} {h}:{i}:{s}'):"");
      this.effectTimeRange.push(this.form.invalidTime !=null?parseTime(this.form.invalidTime, '{y}-{m}-{d} {h}:{i}:{s}') :"");
      const id = row.id
      getAgreement(id).then(response => {
        this.form = response.data;
        this.znAgreementDetailList = response.data.znAgreementDetailList;
        this.znAgreementDetailCollection = this.znAgreementDetailList;
        this.subLoading = false;
        this.form.id = null;
      });
    },
    //商品排序
    handleOrder(table,column){
      this.znAgreementDetailList = this.znAgreementDetailList.sort(this.sortFun(column.property,column.sort === 'descending'))
    },
    sortFun (attr, rev) {
      //第一个参数传入info里的prop表示排的是哪一列，第二个参数是升还是降排序
      if (rev == undefined) {
        rev = 1;
      } else {
        rev = (rev) ? 1 : -1;
      }
      return function (a, b) {
        a = a[attr] !=null ?a[attr]:0;
        b = b[attr] !=null?b[attr]:0;
            return b-a;
        }
    },
    // //会员id转为名称
    customerFormat(row, column) {
      var actions = [];
      this.customers.filter(item => {
      	if (item.id == row.customerId) {
      		actions.push(item.supplier);
      	}
      })
      return actions.join('');
    },
    /** 查询客户协议价管理列表 */
    getList() {
      this.loading = true;
      listAgreement(this.queryParams).then(response => {
         // this.agreementList = response.data;
          // console.log(response.data)
         this.agreementList = this.handleTree(response.data, "id");
         // console.log(this.agreementList)
        // this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.isRealOnly = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        customerId: null,
        effectTime: null,
        invalidTime:null,
        isDefault: null,
        status: "0",
        createTime: null,
        createBy: null,
        createName: null,
        updateTime: null,
        updateBy: null,
        updateName: null,
        tenantId: null,
        deleteFlag: null,
        saleRatio:null,
        znAgreementDetailList:[],
      };
      this.znAgreementDetailList = [];
      this.effectTimeRange = []
      this.resetForm("form");
      this.isRealOnly = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids =[];
      this.disableIds =[];
      this.enableIds =[];
      selection.forEach(item => {
        if(item.parentId ==0 && item.status=='0'){this.disableIds.push(item.id)}
        if(item.parentId ==0 && item.status=='1'){this.enableIds.push(item.id)}
        if(item.parentId ==0 && (item.status =='0' || item.status =='1')){
          this.ids.push(item.id)
        }
      })
      this.single = this.ids.length!==1
      this.multiple = !this.ids.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.saleRatio =1.1;
      this.getMaterialList();
      this.open = true;
      this.title = "添加协议价管理";
      // this.form.effectTime =  parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}');
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.subLoading = true;
      this.open = true;
      this.title = "修改协议价管理";
      this.form = row;
      // this.effectTimeRange.push(this.form.effectTime  !=null?parseTime(this.form.effectTime , '{y}-{m}-{d} {h}:{i}:{s}'):"");
      // this.effectTimeRange.push(this.form.invalidTime !=null?parseTime(this.form.invalidTime, '{y}-{m}-{d} {h}:{i}:{s}') :"");
      const id = row.id || this.ids
      getAgreement(id).then(response => {
        console.log(this.effectTimeRange)
        this.znAgreementDetailList = response.data.znAgreementDetailList;
        this.znAgreementDetailCollection = this.znAgreementDetailList;
        this.subLoading = false;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
         console.log(this.effectTimeRange)
        if (valid) {
          this.form.znAgreementDetailList = this.znAgreementDetailList;
          // if(this.form.title ==null || this.form.title ==""){
          //   this.form.title = this.
          // }
          // if(this.effectTimeRange.length>0){
          //   this.form.effectTime = this.effectTimeRange[0] ;
          //   this.form.invalidTime = this.effectTimeRange[1];
          // }
          if (this.form.id != null) {
            updateAgreement(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAgreement(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除协议价管理编号为"' + ids + '"的数据项？').then(function() {
        return delAgreement(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleDetail(row) {
      this.reset();
      this.subLoading = true;
      this.title = "查看协议价管理";
      this.isRealOnly = true;
      this.form = row;
      this.effectTimeRange.push(this.form.effectTime  !=null?parseTime(this.form.effectTime , '{y}-{m}-{d} {h}:{i}:{s}'):"");
      this.effectTimeRange.push(this.form.invalidTime !=null?parseTime(this.form.invalidTime, '{y}-{m}-{d} {h}:{i}:{s}') :"");
       this.open = true;
      getAgreement(row.id).then(response => {
        this.znAgreementDetailList = response.data.znAgreementDetailList;
        this.znAgreementDetailCollection = this.znAgreementDetailList;
         this.subLoading = false;
      });
    },
	/** 协议商品详情序号 */
    rowZnAgreementDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 协议商品详情添加按钮操作 */
    handleAddZnAgreementDetail() {
          // this.getMaterialList();
    },
    /** 协议商品详情删除按钮操作 */
    handleDeleteZnAgreementDetail() {
      if (this.checkedZnAgreementDetail.length == 0) {
        this.$modal.msgError("请先选择要删除的协议商品详情数据");
      } else {
        const znAgreementDetailList = this.znAgreementDetailList;
        const checkedZnAgreementDetail = this.checkedZnAgreementDetail;
        this.znAgreementDetailList = znAgreementDetailList.filter(function(item) {
          return checkedZnAgreementDetail.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleZnAgreementDetailSelectionChange(selection) {
      this.checkedZnAgreementDetail = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('basicsystem/agreement/export', {
        ...this.queryParams
      }, `agreement_${new Date().getTime()}.xlsx`)
    },
    /** 查询产品列表 */
    getMaterialList() {
      let that = this
      this.subLoading = true;
      this.znAgreementDetailList =[];
      listAllMaterial(this.material.queryParams).then(response => {
        // console.log(response.data);
        this.material.materialList = response.data;
        if(this.material.materialList.length>0){
          this.material.materialList.forEach(function(item,index){
              let obj = {};
              obj.materialId = item.id;
              obj.materialName = item.name;
              obj.materialStandard = item.standard;
              obj.materialModel = item.model;
              obj.materialColor = item.color;
              obj.materialCategoryName = item.categoryName;
              obj.materialUnit = item.unit;
              obj.materialExpiryNum = item.expiryNum;
              obj.materialBarCode = item.znMaterialExtendList[0].barCode;
              obj.materialChineseChar = item.chineseChar
              // obj.materialWholesaleDecimal = item.znMaterialExtendList[0].wholesaleDecimal;
              obj.materialExtendId = item.znMaterialExtendList[0].id;
              obj.purchasePrice = item.znMaterialExtendList[0].purchaseDecimal;
              obj.salePrice = math.format(math.round(math.multiply(math.number(item.znMaterialExtendList[0].purchaseDecimal),math.number(that.form.saleRatio)),2));
              if(obj.salePrice !=null && obj.salePrice >0 && obj.purchasePrice !=null && obj.salePrice > 0){
                // obj.ml = ((( obj.salePrice - obj.purchasePrice)/ obj.salePrice)*100).toFixed(2)+"%"
                obj.mlRatio = math.format(math.round(math.chain(math.number(obj.salePrice)).subtract(math.number(obj.purchasePrice)).divide(math.number(obj.purchasePrice)).done(),4));
              }else{
                obj.mlRatio = 0
              }
              that.znAgreementDetailList.push(obj);
          })
          this.znAgreementDetailCollection = this.znAgreementDetailList;
          console.log(this.znAgreementDetailCollection )
        }
        this.subLoading = false;
      });
    },
    /** 批量操作按钮操作 */
    handleCommand(command) {
      if(command == 'delete'){
        this.handleDelete(this);
      }else if(command == 'enabled'){
         this.handleStatus(1);
      }else if(command == 'disabled'){
        this.handleStatus(2);
      }else if(command == 'effect'){
        this.handleStatus(2);
      }
    },
    /** 审核、反审核按钮操作 */
    handleStatus(status) {
      const statusTxt = status == 0 ? "停用":"启用";
      let ids = [];
      let submit = false;
      if(status ==2){
        if(this.enableIds.length ==0 ){
           this.$modal.msgError("停用，请选择已启用的协议");
           return ;
        }else{
          ids = this.enableIds;
           submit = true;
        }
      }else if(status ==1){
        if(this.disableIds.length ==0){
           this.$modal.msgError("启用，请选择未启用的协议");
           return ;
        }else{
          ids = this.disableIds;
           submit = true;
        }
      }

      if(submit){
        this.$modal.confirm('是否确认'+statusTxt+' 编号为"' + ids + '"的单据？').then(function() {
          return updateAgreementStatus(ids,status);
        }).then((res) => {
        		this.getList();
        		if(res.code == 200){
        			this.$modal.msgSuccess(res.msg);
        		}else{
        			this.$modal.msgError(res.msg);
        		}
        }).catch(() => {});
      }
    },
    handleEffect(row){
       updateAgreementStatus(row.id,'2').then(response =>{
          this.$modal.msgSuccess(row.title+"-已立即生效成功");
          this.open = false;
          this.getList();
      });
    },
    /**
     * 计算毛利
     * @param {Object} row
     * @param {Object} index
     */
    changeML(row,index){
      row.mlRatio= (row.salePrice-row.purchasePrice)/row.salePrice;
      if(this.isSearch){
        let tempList = this.znAgreementDetailList.map(item => {
          console.log(row.materialId+","+item.materialId)
          if(item.materialId ===row.materialId){
            item.ml = row.ml;
            item.salePrice = row.salePrice;
          }
          return item;
        } );
        this.znAgreementDetailList = tempList;
      }
    },
    handleMaterialQuery(){
      let name = this.material.queryParams.name;
      if(name){
        this.isSearch = true;
        if(this.znAgreementDetailList.length>0){
         this.znAgreementDetailCollection = this.znAgreementDetailList.filter(detail => detail.materialName.indexOf(name)>-1 || detail.materialBarCode.indexOf(name)>-1 || detail.materialChineseChar.indexOf(name.trim().toUpperCase())>-1)
        }
      }else{
         this.isSearch = false;
          this.znAgreementDetailCollection = this.znAgreementDetailList;
      }
    },
    refreshMaterialQuery(){
      let that = this
      this.subLoading = true;
      // this.znAgreementDetailList =[];
      listAllMaterial(this.material.queryParams).then(response => {
        // console.log(response.data);
        this.material.materialList = response.data;
        if(this.material.materialList.length>0){
          for(let item of this.material.materialList){
            let isNew = true;
            for(let item1 of that.znAgreementDetailList){
               console.log(item.id+","+item1.materialId +",("+item1.materialExtendId+","+item.znMaterialExtendList[0].id+"),"+isNew)
                if(item1.materialId == item.id && item1.materialExtendId == item.znMaterialExtendList[0].id){
                  let isNew = false;
                  break
                }
            }
            // console.log(item.id+","+item.name+","+item.znMaterialExtendList[0].id+","+isNew)
            if(isNew){
              let obj = {};
              obj.materialId = item.id;
              obj.materialName = item.name;
              obj.materialStandard = item.standard;
              obj.materialModel = item.model;
              obj.materialColor = item.color;
              obj.materialCategoryName = item.categoryName;
              obj.materialUnit = item.unit;
              obj.materialExpiryNum = item.expiryNum;
              obj.materialBarCode = item.znMaterialExtendList[0].barCode;
              obj.materialChineseChar = item.chineseChar
              // obj.materialWholesaleDecimal = item.znMaterialExtendList[0].wholesaleDecimal;
              obj.materialExtendId = item.znMaterialExtendList[0].id;
              obj.purchasePrice = item.znMaterialExtendList[0].purchaseDecimal;
              obj.salePrice = math.format(math.round(math.multiply(math.number(item.znMaterialExtendList[0].purchaseDecimal),math.number(that.form.saleRatio)),2));
              if(obj.salePrice !=null && obj.purchasePrice !=null){
                // obj.ml = ((( obj.salePrice - obj.purchasePrice)/ obj.salePrice)*100).toFixed(2)+"%"
                obj.mlRatio = math.format(math.round(math.chain(math.number(obj.salePrice)).subtract(math.number(obj.purchasePrice)).divide(math.number(obj.salePrice)).done(),4));
              }
              that.znAgreementDetailList.push(obj);
            }
          }
          this.znAgreementDetailCollection = this.znAgreementDetailList;
          console.log(this.znAgreementDetailCollection )
        }
        this.subLoading = false;
      });
    },
    resetMaterialQuery(){
      this.isSearch = false;
      this.znAgreementDetailCollection = this.znAgreementDetailList;
    },
    handleCustomer(row){
      this.customerOpen = true;
      this.customerForm.agreementId = row.id
      this.customerForm.customerList =[];
      this.customerForm.customerIdList =[];
      // if(this.ids.length==1){
        selectCustomerListByAgreementId(row.id).then(response =>{
          // console.log(response.data)
           this.customerForm.customerList = response.data;
           this.customerForm.isUpdate = this.customerForm.customerList.length>0
        });
      // }
    },
    submitCustomerForm(){
      // this.$refs.customerForm.validate(async(valid) => {
      //   console.log(valid)
      //         // 校验通过
      //         if(valid){

      //         }
      // })
      if(this.customerForm.customerList.length>0){
        // let isNull = this.customerForm.customerList.filter(item => item.customerId == null)
        // if(isNull.length==0){
          this.$refs["customerForm"].validate(valid => {
             console.log(this.customerForm)
            if (valid) {
              doCustomer(this.customerForm).then(response=>{
                    this.$modal.msgSuccess("用户协议设置成功");
                    this.customerOpen =  false;
                    this.getList();
              });
            }
          })
        // }else{
        //   this.$modal.msgError("请先选择客户");
        // }
      }else{
         this.$modal.msgError("请先新增客户");
      }
    },
     customerCancel(){
       this.customerOpen = false;
     },
     changePurchasePrice(){
       if(this.znAgreementDetailCollection.length>0){
         let saleRatioNew = this.form.saleRatio;
         // console.log(saleRatioNew)
         this.znAgreementDetailCollection.forEach(function(item,index){
            item.salePrice = math.format(math.round(math.multiply(math.number(item.salePrice),math.number(saleRatioNew)),2));
            if(item.purchasePrice !=null && item.purchasePrice>0){
              item.mlRatio = math.format(math.round(math.chain(math.number(item.salePrice)).subtract(math.number(item.purchasePrice)).divide(math.number(item.salePrice)).done(),4));
            }else{
              item.mlRatio = math.format(1,4);
            }
          });
         console.log(this.znAgreementDetailCollection)
       }
     }
  }
};
</script>
